package com.ll.ztest;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

public class WebSocketServer extends WebSocketServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7332780600443604660L;
	
	/**
	 * 保存WsOutbound
	 */
	public final Map<Integer, WsOutbound> map = new HashMap<Integer, WsOutbound>();
	
	
	@Override
	protected StreamInbound createWebSocketInbound(String arg0,
			HttpServletRequest arg1)
	{
		return new ChatMessgageInbound(this);
	}
}

class ChatMessgageInbound extends MessageInbound
{
	WebSocketServer server = null;
	
	public ChatMessgageInbound(WebSocketServer server)
	{
		this.server = server;
	}
	
	@Override
	protected void onOpen(WsOutbound outbound)
	{
		this.server.map.put(outbound.hashCode(), outbound);
		
		super.onOpen(outbound);
	}
	
	@Override
	protected void onClose(int status)
	{
		this.server.map.remove(this.getWsOutbound().hashCode());
		
		super.onClose(status);
	}
	
	@Override
	protected void onTextMessage(CharBuffer buffer) throws IOException
	{
		String msg = buffer.toString();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		msg = this.getWsOutbound().hashCode() + sdf.format(date) + "\n" + msg;
		broadcast(msg);
	}
	
	@Override
	protected void onBinaryMessage(ByteBuffer buffer) throws IOException
	{
		
	}
	
	private void broadcast(String msg) 
	{
		Set<Integer> set = this.server.map.keySet();
		for (Integer integer : set) 
		{
			WsOutbound outbound = this.server.map.get(integer);
			CharBuffer buffer = CharBuffer.wrap(msg);
			try 
			{
				outbound.writeTextMessage(buffer);
				outbound.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
